package cn.itcast.web.controller.cargo;

import cn.itcast.common.utils.ImageUploadUtils;
import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    //查询分页
    @RequestMapping("/list")
    public String list(String contractId , @RequestParam(defaultValue = "1")int page ,@RequestParam(defaultValue = "5")int size){
        //构造货物列表
        //1.创建example
        ContractProductExample example = new ContractProductExample();
        //2.创建criteria
        ContractProductExample.Criteria criteria = example.createCriteria();
        //3.添加查询条件
        criteria.andContractIdEqualTo(contractId);

        PageInfo pageInfo = contractProductService.findAll(example,page,size);
        request.setAttribute("page",pageInfo);

        //查询所有的生产厂家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria1 =factoryExample.createCriteria();
        criteria1.andCtypeEqualTo("货物");

        List factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        //将购销合同id存入request
        request.setAttribute("contractId",contractId);
        return "/cargo/product/product-list";
    }

    //跳转更新页面
    @RequestMapping("toUpdate")
    public String toUpdate(String id){
        //根据id查询 进行回显
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        //查询所有的厂家列表
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria = factoryExample.createCriteria();
        criteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);
        return "/cargo/product/product-update";
    }


    //保存 或 更新
    //添加文件上传支持
    /**
     * 页面修改enctype属性
     * 配置文件解析器
     * 将上传的文件转为为MultipartFile对象
     */
    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct , MultipartFile productPhoto) throws IOException{
        contractProduct.setCompanyId(getLoginCompanyName());
        contractProduct.setCompanyName(getLoginCompanyName());

        if (StringUtils.isEmpty(contractProduct.getId())){
            if (productPhoto != null && productPhoto.isEmpty() ){
                String url = new ImageUploadUtils().upload(productPhoto.getBytes());
                contractProduct.setProductImage(url);
            }
            contractProductService.save(contractProduct);
        }else{
            contractProductService.update(contractProduct);
        }
        //页面重定向
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }
    //删除货物
    @RequestMapping("/delete")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    /**
     *跳转上传页面
     *      参数： 购销合同ID
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    /**
     * Excel文件上传：批量保存货物
     *      参数：
     *          1.购销合同id
     *          2.文件对象MultipartFile
     */
    @RequestMapping("/import")
    public String importExcel(String contractId,MultipartFile file)throws IOException{
        List<ContractProduct> list = new ArrayList<ContractProduct>();
        //1.解析Excel文件
        //1.1根据上传的文件，构建excel的工作薄
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        //1.2获取excel中的第一页
        Sheet sheet = workbook.getSheetAt(0);
        //1.3循环所有的数据行
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            //1.4 循环每行中的每一个单元格
            Object[] objects = new Object[10];  // {null,"升华",”xx001“,1,"pcs",null,null,null,null,null}
            for (int j = 1 ;j < row.getLastCellNum(); j++){
                Cell cell = row.getCell(j);
                objects[j] = getCellValue(cell); //调用解析方法
            }
            //1.5构造货物对象
            ContractProduct contractProduct = new ContractProduct(
                    objects,getLoginCompanyId(),getLoginCompanyName());
            contractProduct.setContractId(contractId);//设置货物所属的购销合同id

            //2.将解析的数据转化为货物的list集合
            list.add(contractProduct);
        }
        //3.调用service批量保存货物
        contractProductService.saveAll(list);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    private Object getCellValue(Cell cell){
        Object obj = null;
        //1.获取单元格的数据类型
        CellType cellType = cell.getCellType();
        //2.根据不同数据类型，调用不同的方法获取数据
        switch(cellType){
            case STRING:{ //字符串
                obj = cell.getStringCellValue();
                break;
            }
            case NUMERIC:{//数字类型（1.数字 ，2 日期）
                //判断数字是否属于日期类型
                if (DateUtil.isCellDateFormatted(cell)){
                    //日期
                obj = cell.getDateCellValue();
                }else{
                    //数字
                    obj = cell.getNumericCellValue();
                }
                break;
            }
            case BOOLEAN:{//boolean类型
                obj = cell.getBooleanCellValue();
                break;
            }
            case FORMULA:{//表达式
               break;
            }
            default:{
                break;
            }
        }
        return obj;
    }

}

